'use strict';

const db = uniCloud.database();
const collection = db.collection('food-dishes');

exports.main = async (event, context) => {
  try {
    // 获取所有菜品总数
    const totalResult = await collection.count();
    const total = totalResult.total;
    
    // 获取推荐菜品数
    const recommendedResult = await collection.where({
      is_recommended: true
    }).count();
    const recommendedCount = recommendedResult.total;
    
    // 获取非推荐菜品数
    const notRecommendedResult = await collection.where({
      is_recommended: false
    }).count();
    const notRecommendedCount = notRecommendedResult.total;
    
    // 获取按辣度分组的统计
    const spicinessStats = {};
    for (let i = 0; i <= 2; i++) {
      const result = await collection.where({
        spiciness: i
      }).count();
      spicinessStats[i] = result.total;
    }
    
    // 获取按分类分组的统计
    const allDishes = await collection.get();
    const categoryStats = {};
    
    allDishes.data.forEach(dish => {
      const categoryId = dish.category_id;
      if (!categoryStats[categoryId]) {
        categoryStats[categoryId] = 0;
      }
      categoryStats[categoryId]++;
    });
    
    // 获取最近创建的5个菜品
    const recentDishes = await collection
      .orderBy('create_date', 'desc')
      .limit(5)
      .get();
    
    // 获取创建时间分布（按月份）
    const monthlyStats = {};
    
    allDishes.data.forEach(dish => {
      const createDate = new Date(dish.create_date.$date);
      const monthKey = `${createDate.getFullYear()}-${String(createDate.getMonth() + 1).padStart(2, '0')}`;
      
      if (!monthlyStats[monthKey]) {
        monthlyStats[monthKey] = 0;
      }
      monthlyStats[monthKey]++;
    });
    
    // 转换为数组格式
    const monthlyStatsArray = Object.keys(monthlyStats).map(month => ({
      month,
      count: monthlyStats[month]
    })).sort((a, b) => a.month.localeCompare(b.month));
    
    return {
      code: 200,
      message: '统计获取成功',
      data: {
        summaryStats: {
          totalDishes: total,
          recommendedDishes: recommendedCount,
          notRecommendedDishes: notRecommendedCount,
          recommendedPercentage: total > 0 ? Math.round((recommendedCount / total) * 100) : 0
        },
        spicinessStats,
        categoryStats,
        recentDishes: recentDishes.data,
        monthlyStats: monthlyStatsArray,
        summary: {
          totalDishes: total,
          recommendedDishes: recommendedCount,
          lastUpdated: Date.now()
        }
      }
    };
  } catch (error) {
    return {
      code: 500,
      message: '统计获取失败',
      data: null
    };
  }
};